package com.su.song.dataapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences preferences;
    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ck_select;
    private Button btn_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取四个输入框
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        //选择按钮
        ck_select = findViewById(R.id.ck_select);
        //保存信息按钮
        btn_confirm = findViewById(R.id.btn_confirm);

        //建立共享参数
        preferences = getSharedPreferences("X-3", MODE_PRIVATE);
        reload();

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                   String name = et_name.getText().toString();
                   String age = et_age.getText().toString();
                   String height = et_height.getText().toString();
                   String weight = et_weight.getText().toString();

                   //建立操作编辑器对共享参数进行操作,共享参数以键值对的形式保存数据
                SharedPreferences.Editor edit = preferences.edit();
                edit.putString("name",name);
                edit.putInt("age",Integer.parseInt(age));
                edit.putFloat("height",Float.parseFloat(height));
                edit.putFloat("weight",Float.parseFloat(weight));
                edit.putBoolean("married", ck_select.isChecked());
                edit.commit();//将信息提交保存

                Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void reload() {
        String name = preferences.getString("name", null);
        if(name != null){
            et_name.setText(name);
        }
        int age = preferences.getInt("age",0);
        if( age != 0){
            et_age.setText(String.valueOf(age));
        }
        float height = preferences.getFloat("height",0f);
        if(height != 0f){
            et_height.setText(String.valueOf(height));
        }
        float weight = preferences.getFloat("weight", 0f);
        if(weight != 0f){
            et_weight.setText(String.valueOf(weight));
        }
        boolean married = preferences.getBoolean("married",false);
        ck_select.setChecked(married);
    }
}